﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RestSharp;
using RestSharp.Contrib;
using System.Configuration;
using System.Net;
using MsForgeReboot.Framework.Entities;
using MsForgeReboot.Framework.TownCrierChannelTools;
using MsForgeReboot.Framework.Interfaces;


namespace MsForgeReboot.Framework.TownCrierChannels {
    [Serializable]
    public class FacebookChannel : IChannel {


        private FacebookChannelSection _settings;
        private RestTransport _transport;
        public Event Source { get; set; }

        public FacebookChannel() :
            this(new RestClient(), new RestRequest(), "FacebookChannelSection") { }


        
        public FacebookChannel(IRestClient client, IRestRequest request, FacebookChannelSection section) {
            _settings = section;
            this._transport = new RestTransport(client, request);
        }
        
        
        public FacebookChannel(IRestClient client, IRestRequest request, string sectionName) {
            _settings = ConfigurationManager.GetSection(sectionName) as FacebookChannelSection;
        }


        #region IChannel Members

        public DeliveryResult DeliverEvent(Event source) {
            Parameter[] param = FormattingTools.FormatEventForFacebook(source).
                Select((KeyValuePair<string, object> item) => new Parameter { Name = item.Key, Value = item.Value, Type = ParameterType.GetOrPost }).ToArray();

            IAuthenticator auth = new OAuth2UriQueryParameterAuthenticator(_settings.OauthToken.AccessToken);

            DeliveryResult result = this._transport.Post(_settings.ApiBaseUrl.Value, _settings.ApiPostResource.Value, auth, param);
            result.DeliveryChannel = "Facebook Channel";
            return result;
        }

        public DeliveryResult DeliverEvent() {
            //throw new NotImplementedException();
            return this.DeliverEvent(this.Source);
        }


        #endregion
    }
}
